package com.qf.netty.channel;

import com.google.gson.Gson;
import com.qf.entity.netty.ChatMsg;
import com.qf.entity.netty.ConnMsg;
import com.qf.entity.netty.HeartMsg;
import com.qf.entity.netty.NettyMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * @Description:
 * @Author: xbb
 * @Date:2020/4/20
 */
public class WebSocketChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        System.out.println("客户端发送的数据："+text);
        Gson gson = new Gson();

        //根据不同的类型转化成不同的对象
        //将其交给对应的handler处理
        //把json字符串转成对象
        NettyMsg nettyMsg = gson.fromJson(text, NettyMsg.class);
        if(nettyMsg.getType()==1){  //新的连接
            nettyMsg = gson.fromJson(text, ConnMsg.class);
        } else if (nettyMsg.getType()==2){
            nettyMsg = gson.fromJson(text, HeartMsg.class);
        } else if(nettyMsg.getType()==3){
            nettyMsg = gson.fromJson(text, ChatMsg.class);
        }

        //往下传递
        channelHandlerContext.fireChannelRead(nettyMsg);
    }


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
//        System.out.println("新客户端连接。。");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端断开连接。。");
    }
}
